package top.infopub.mgr.util;


import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import top.infopub.util.DateUtil;
import top.infopub.zookeeper.ZookeeperConst;


/**
 * 设置Zookeeper Node数据工具类
 * @author Awoke
 * @version 2018年10月15日
 * @see ZKPathsUtil
 * @since
 */
@Component
public class ZKPathsUtil {

    @Autowired
    private CuratorFramework curatorFramework;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static String prePath = ZookeeperConst.CONFIG_PATH + "dataChangeNotice/";

    /**
     * ZooKeeper节点路径枚举类
     * @author zhuo
     * @version 1.0
     */
    public static enum Zkpath {
        /**
         * 权限信息
         */
        operatorPurview(prePath + "operatorPurview"),
        /**
         * 前台会员权限信息
         */
        frontPurview(prePath + "frontPurview"),
        /**
         * 数据字典
         */
        dataDic(prePath + "dataDic"),
        /**
         * 业务参数
         */
        bizParameter(prePath + "bizParameter"),
        /**
         * 消息服务提供商
         */
        mgcPartnerInfo(prePath + "mgcPartnerInfo"),
        /**
         * 消息模板
         */
        mgcTemplate(prePath + "mgcTemplate"),
        
        /**
         * 节日
         */
        holiday(prePath + "holiday");

        private final String name;

        private Zkpath(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }
    }

    /**
     * 创建或更新一个节点
     * @param 
     * @return 是否成功
     */
    public Boolean createrOrUpdate(Zkpath zkPath) {
        try {
            // 检查是否存在
            if (curatorFramework.checkExists().forPath(zkPath.name) == null) {
                curatorFramework.create().forPath(zkPath.name,
                    DateUtil.currentDate(DateUtil.DATE_STYLE_BASIC_SS).getBytes());
            }
            else {
                curatorFramework.setData().forPath(zkPath.name,
                    DateUtil.currentDate(DateUtil.DATE_STYLE_BASIC_SS).getBytes());
            }
            logger.info("Zookeeper 创建或更新节点:" + zkPath.name);
            return true;
        }
        catch (Exception e) {
            logger.error("", e);
            return false;
        }
    }

}
